<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { scrapProductApi } from '#/api/production/productState';

import { useScrapSchema } from '../data';

const emit = defineEmits<{
  success: [];
}>();

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: useScrapSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (valid) {
      modalApi.lock();
      const data = await formApi.getValues();
      try {
        await scrapProductApi(
          data.id,
          data.scrapCategory,
          data.scrapCategoryName,
          data.scrapReason,
        );
        modalApi.close();
        emit('success');
      } finally {
        modalApi.unlock();
      }
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<Record<string, any>>();
      formApi.setValues(data, false);
    }
  },
  title: '确定要强制报废 ?',
});
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>
